import React, { useState, useEffect } from 'react';
import { useParams } from "react-router";
import { Button, Radio, Input, DatePicker, Menu, Dropdown, Modal, notification, message, Space } from 'antd';
import edit from '../../assets/edit.svg';
import API_ROOT from 'src/api/network';
import { API } from 'src/typings';
import axios from 'axios';
import TitleBar from '../../components/titlebar';
import './index.css';
import moment from 'moment';
import format from 'date-format';


type DetailsProps = {
    params: {
        id: string
    }
}

function disableDate(current) {
    return current && current >= moment().endOf('day');
}

type DetailsState = {
    id: number,
    edit: boolean;
    avatar: string,
    username: string,
    nickname: string,
    birthday: number,
    createTime: number,
    userComment: string,
    updateTime: number,
    gender: number,
    deleted: boolean,
    active: boolean,
    isModalVisible: boolean
}

const error = () => {
    message.error('保存用户信息失败!');
};


class Details extends React.Component<DetailsProps, DetailsState> {
    state = {
        id: -1,
        edit: true,
        avatar: '',
        username: '',
        nickname: '',
        gender: 2,
        birthday: 0,
        createTime: 0,
        userComment: '',
        updateTime: 0,
        deleted: false,
        active: true,
        isModalVisible: false
    };

    componentDidMount() {
        let id = this.props.params.id;
        axios.request({
            url: `${API_ROOT}/users/${id}`,
            method: 'GET'
        }).then(res => {
            let user = res.data as API.User;
            this.setState({
                id: user.id,
                avatar: user.avatar,
                username: user.username,
                nickname: user.nickname,
                gender: user.gender,
                createTime: user.createTime,
                updateTime: user.updateTime,
                deleted: user.deleted,
                active: user.active,
                userComment: user.userComment,
                birthday: user.birthday
            })
        }).catch(err => {
            console.log("request error");
        })
    }

    showModal = () => {
        this.setState({
            isModalVisible: true
        })
    };

    handleDeleteOk = () => {
        this.setState({
            isModalVisible: false
        });
        axios.request({
            url: `${API_ROOT}/users/${this.state.id}`,
            method: 'DELETE'
        }).then(res => {
            if (res.status === 204) {
                message.success('逻辑删除用户成功!')
            }
        })
    };

    handleCancel = () => {
        this.setState({
            isModalVisible: false
        })
    };

    editUser = () => {
        this.setState({
            edit: false
        })
    }

    setGender = ({ key }) => {
        if (key === '0') {
            this.setState({
                gender: 0
            });
        } else if (key === '1') {
            this.setState({
                gender: 1
            })
        } else {
            this.setState({
                gender: 2
            })
        }
    }

    setDelete = ({ key }) => {
        if (key === '1') {
            this.setState({
                deleted: true
            })
        } else {
            this.setState({
                deleted: false
            })
        }
    }


    setActive = ({ key }) => {
        if (key === '1') {
            this.setState({
                active: true
            })
        } else {
            this.setState({
                active: false
            })
        }
    }

    saveUser = () => {
        console.log(new Date(this.state.birthday))
        let user: API.UpdateUserVO = {
            avatar: this.state.avatar,
            username: this.state.username,
            nickname: this.state.nickname,
            gender: this.state.gender,
            birthday: this.state.birthday,
            userComment: this.state.userComment,
            active: this.state.active
        }

        axios.request({
            url: `${API_ROOT}/users/${this.state.id}`,
            method: 'PUT',
            data: user
        }).then(res => {
            if (res.status === 205) {
                message.success('修改用户信息成功!')
                this.setState({
                    edit: true
                })
            }
        }).catch(err => {
            error();
        })
    }

    setNickname = (name: any) => {
        this.setState({
            nickname: name
        });
    }

    setUsername = (name: any) => {
        this.setState({
            username: name
        })
    }

    setUserComment = (comment: any) => {
        this.setState({
            userComment: comment
        })
    }

    setBirthday = (moment: moment.Moment) => {
        console.log(moment);
        this.setState({
            birthday: moment.toDate().getTime()
        })
    }

    render() {
        const genderMenu = (
            <Menu onClick={this.setGender}>
                <Menu.Item key="0">
                    男
                </Menu.Item>
                <Menu.Item key="1">
                    女
                </Menu.Item>
                <Menu.Item key="2">
                    未知
                </Menu.Item>
            </Menu>
        );

        const activeMenu = (
            <Menu onClick={this.setActive}>
                <Menu.Item key="1">
                    是
                </Menu.Item>
                <Menu.Item key="2">
                    否
                </Menu.Item>
            </Menu>
        );
        const deleteMenu = (
            <Menu onClick={this.setDelete}>
                <Menu.Item key="1">
                    是
                </Menu.Item>
                <Menu.Item key="2">
                    否
                </Menu.Item>
            </Menu>
        );




        return <div className="details-container">
            <TitleBar title="用户详情"></TitleBar>
            <div className="content">
                <div className="first line">
                    <div className="avatar-username">
                        <div className="avatar">
                            <img className="user-avatar-image" src={this.state.avatar} alt="avatar" />
                            <div className="edit-avatar">
                            </div>
                        </div>

                        <div className="username-label">
                            Mary
                        </div>
                    </div>
                    <div className="edit-user" onClick={this.editUser}>
                        <img src={edit} alt="" />
                    </div>
                </div>

                <div className="second line">
                    <div className="username-input details-input">
                        <div className="label">
                            姓名
                        </div>
                        <Input placeholder="Basic usage" onChange={this.setUsername} value={this.state.username} disabled={this.state.edit} />
                    </div>

                    <div className="nickname-input details-input">
                        <div className="label">
                            昵称
                        </div>
                        <Input placeholder="Basic usage" onChange={this.setNickname} value={this.state.nickname} disabled={this.state.edit} />
                    </div>

                    <div className="gender-input details-input">
                        <div className="label">
                            性别
                        </div>
                        <Dropdown overlay={genderMenu} placement="bottomCenter" arrow disabled={this.state.edit} >
                            <Button>{this.state.gender === 0 ? '男' : this.state.gender === 1 ? '女' : '未知'}</Button>
                        </Dropdown>
                    </div>
                </div>

                <div className="third line">
                    <div className="birthday-input details-input">
                        <div className="label">
                            出生日期
                        </div>

                        <DatePicker className="birthday-picker" disabled={this.state.edit} onChange={this.setBirthday} onOk={this.setBirthday} disabledDate={disableDate} defaultValue={moment(format.asString('yyyy/MM/dd', new Date(this.state.birthday)), 'YYYY/MM/DD')} />
                    </div>

                    <div className="create-time-input details-input">
                        <div className="label">
                            创建时间
                        </div>

                        <Input placeholder="Basic usage" value={format.asString('yyyy/MM/dd hh:mm:ss', new Date(this.state.createTime))} disabled />
                    </div>

                    <div className="update-time-input details-input">
                        <div className="label">
                            修改时间
                        </div>
                        <Input placeholder="Basic usage" value={format.asString('yyyy/MM/dd hh:mm:ss', new Date(this.state.updateTime))} disabled />
                    </div>
                </div>

                <div className="forth line">
                    <div className="user-comment-input details-input">
                        <div className="label">
                            备注
                        </div>
                        <Input placeholder="Basic usage" onChange={this.setUserComment} value={this.state.userComment} disabled={this.state.edit} />
                    </div>

                    <div className="is-active-input details-input">
                        <div className="label">是否启用</div>
                        <Dropdown overlay={activeMenu} placement="bottomCenter" arrow disabled={this.state.edit} >
                            <Button>{this.state.active ? '是' : '否'}</Button>
                        </Dropdown>
                    </div>

                    <div className="is-delete-input details-input">
                        <div className="label">是否删除</div>
                        <Dropdown overlay={deleteMenu} placement="bottomCenter" arrow disabled={this.state.edit} >
                            <Button>{this.state.deleted ? '是' : '否'}</Button>
                        </Dropdown>
                    </div>
                </div>
            </div>

            <div className="user-actions">
                <div className="delete-button">
                    <Button type="primary" shape="round" size="large" danger onClick={this.showModal}>删除</Button>
                </div>

                <div className="save-button">
                    <Button type="primary" shape="round" size="large" disabled={this.state.edit} onClick={this.saveUser}>保存</Button>
                </div>
            </div>

            <Modal title="Basic Modal" visible={this.state.isModalVisible} onOk={this.handleDeleteOk} onCancel={this.handleCancel}>
                确认删除用户?
            </Modal>
        </div>;
    }
}


const DetailsPage = (props) => (
    <Details
        {...props}
        params={useParams()}
    />
);

export default DetailsPage;